﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusStopDataAccess;

namespace BusStopWebApp.Services
{
    public static class Serializer
    {
        public static IEnumerable<JSONBusStop> Serialize(IEnumerable<BusStops> stops)
        {
            return new List<JSONBusStop>(from stop in stops select Serialize(stop));
        }
        public static JSONBusStop Serialize(BusStops stop)
        {
            return new JSONBusStop()
            {
                Code = stop.Code.ToString(),
                Description = stop.Name,
                Lattitude = stop.Latitude,
                Longitude = stop.Longitude
            };
        }
        public static JSONStopSummary Serialize(BusStops stop, IEnumerable<Routes> routes)
        {
            JSONStopSummary summary = new JSONStopSummary();
            summary.Stop = Serialize(stop);
            summary.Routes.AddRange(Serialize(routes));
            summary.Trips = null;
            return summary;
        }
        public static IEnumerable<JSONRoute> Serialize(IEnumerable<Routes> routes)
        {
            return from route in routes
                   select Serialize(route);
        }
        public static JSONRoute Serialize(Routes route)
        {
            return new JSONRoute()
            {
                Code = route.Code,
                Name = route.Name
            };
        }
        public static JSONStopSummary Serialize(BusStops stop, Dictionary<Routes, IEnumerable<Departures>> departures, IEnumerable<Routes> routes)
        {
            JSONStopSummary summary = Serialize(stop, departures);
            summary.Routes = new List<JSONRoute>(Serialize(routes));
            return summary;
        }
        public static JSONStopSummary Serialize(BusStops stop, Dictionary<Routes, IEnumerable<Departures>> departures)
        {
            JSONStopSummary summary = new JSONStopSummary();
            summary.Stop = Serialize(stop);
            summary.Routes = null;

            foreach (Routes route in departures.Keys)
            {
                List<TimeSpan> times = new List<TimeSpan>();
                IEnumerable<Departures> trips = departures[route];
                foreach (Departures departure in trips)
                {
                    times.Add(CropAndConvertTime( departure.Time));
                }
                summary.Trips.Add(route.Code + " "+route.Name, times);                
            }
            return summary;
        }

        private static TimeSpan CropAndConvertTime(int minutes)
        {
            TimeSpan temp = TimeSpan.FromMinutes(minutes);
            while (temp.TotalDays > 1)
            {
                temp = temp.Subtract(TimeSpan.FromDays(1));
            }
            return temp;
        }
    }
}
